package com.zws.cucumber.plugin.procedure;

import com.zws.cucumber.var.ZwsVarBlock;
import com.zws.cucumber.var.ZwsVarBlockContext;
import org.apache.commons.collections4.MapUtils;

import java.util.Map;

public class ZwsProcedureStackFrame implements ZwsVarBlockContext {
    private int level;
    final private String procedureName;
    final private Map<String, String> argumentMap;

    private Object result;

    private ZwsVarBlock varBlock;

    public ZwsProcedureStackFrame(String procedureName, Map<String, String> argumentMap) {
        this.procedureName = procedureName;
        this.argumentMap = argumentMap;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public int getLevel() {
        return level;
    }

    public String getProcedureName() {
        return procedureName;
    }

    public Map<String, String> getArgumentMap() {
        return argumentMap;
    }

    public ZwsVarBlock getVarBlock() {
        return varBlock;
    }

    public void setVarBlock(ZwsVarBlock varBlock) {
        this.varBlock = varBlock;
        this.varBlock.setContext(this);
        if (MapUtils.isNotEmpty(argumentMap)) {
            this.varBlock.putAll(argumentMap);
        }
    }

    public Object getResult() {
        return result;
    }

    public void setResult(Object result) {
        this.result = result;
    }

    public String shortDesc() {
        StringBuilder sb = new StringBuilder();
        if (argumentMap != null && !argumentMap.isEmpty()) {
            argumentMap.forEach((k, v) -> {
                sb.append(k)
                        .append("=")
                        .append(v != null && v.length() > 32 ? v.substring(0, 32) + "..." : v)
                        .append(",");
            });
        }
        if (!sb.isEmpty()) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return "#" + level + " " + procedureName + "(" + sb + ")";
    }

    @Override
    public String contextDescription() {
        return shortDesc();
    }
}
